package com.work.yshop.mvp.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.ArticleContract;
import com.work.yshop.mvp.contract.LoginContract;
import com.work.yshop.provider.ArticleProvider;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章数据模型，负责与数据库交互
 */
public class ArticleModel implements ArticleContract.Model {

    private static final String TAG = "ArticleModel";
    private ContentResolver contentResolver;
    private Context context;

    public ArticleModel(Context context) {
        this.context = context;
        this.contentResolver = context.getContentResolver();
    }

    @Override
    public List<Article> getArticleList() {
        // 默认返回最新文章
        return getArticleListByTab(ArticleContract.TAB_LATEST);
    }
    
    @Override
    public List<Article> getArticleListByTab(int tabType) {
        List<Article> articles = new ArrayList<>();
        
        String selection = null;
        String[] selectionArgs = null;
        
        // 获取当前用户类型
        int userType = UserSession.getInstance().getUserType();
        
        // 根据标签类型设置不同的查询条件
        switch (tabType) {
            case ArticleContract.TAB_FOLLOW:
                // 关注的文章 - 这里可以根据用户关注的作者来筛选
                selection = "is_followed = ? AND user_type = ?";
                selectionArgs = new String[]{"1", String.valueOf(userType)};
                break;
                
            case ArticleContract.TAB_LATEST:
                // 最新文章 - 按用户类型筛选
                selection = "user_type = ?";
                selectionArgs = new String[]{String.valueOf(userType)};
                break;
                
            case ArticleContract.TAB_MINE:
                // 我的文章 - 根据当前用户ID筛选
                int userId = UserSession.getInstance().getUserId();
                selection = "user_id = ? AND user_type = ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType)};
                break;
        }

        try {
            // 查询ContentProvider获取文章
            Cursor cursor = contentResolver.query(
                    ArticleProvider.CONTENT_URI,
                    null,
                    selection,
                    selectionArgs,
                    "publish_date DESC" // 按发布日期降序排序
            );

            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        // 从Cursor中提取文章数据
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
                        String summary = cursor.getString(cursor.getColumnIndexOrThrow("summary"));
                        String content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
                        String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
                        String publishDate = cursor.getString(cursor.getColumnIndexOrThrow("publish_date"));
                        int viewCount = cursor.getInt(cursor.getColumnIndexOrThrow("view_count"));
                        String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));

                        // 创建文章对象
                        Article article = new Article();
                        article.setId(id);
                        article.setTitle(title);
                        article.setSummary(summary);
                        article.setContent(content);
                        article.setImageUrl(imageUrl);
                        article.setPublishDate(publishDate);
                        article.setViewCount(viewCount);
                        article.setCategory(category);

                        // 添加到列表
                        articles.add(article);
                    }
                } finally {
                    cursor.close();
                }
            }

            Log.d(TAG, "加载文章数量: " + articles.size());
        } catch (Exception e) {
            Log.e(TAG, "加载文章异常", e);
        }
        
        // 如果没有真实数据，生成一些模拟数据用于展示
        if (articles.isEmpty()) {
            articles = generateMockArticles(tabType);
        }

        return articles;
    }
    
    @Override
    public List<Article> searchArticles(String keyword) {
        List<Article> articles = new ArrayList<>();

        try {
            // 构建搜索条件
            String selection = "title LIKE ? OR content LIKE ?";
            String[] selectionArgs = new String[]{"%" + keyword + "%", "%" + keyword + "%"};
            
            // 查询ContentProvider获取符合条件的文章
            Cursor cursor = contentResolver.query(
                    ArticleProvider.CONTENT_URI,
                    null,
                    selection,
                    selectionArgs,
                    "publish_date DESC" // 按发布日期降序排序
            );

            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        // 从Cursor中提取文章数据
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
                        String summary = cursor.getString(cursor.getColumnIndexOrThrow("summary"));
                        String content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
                        String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
                        String publishDate = cursor.getString(cursor.getColumnIndexOrThrow("publish_date"));
                        int viewCount = cursor.getInt(cursor.getColumnIndexOrThrow("view_count"));
                        String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));

                        // 创建文章对象
                        Article article = new Article();
                        article.setId(id);
                        article.setTitle(title);
                        article.setSummary(summary);
                        article.setContent(content);
                        article.setImageUrl(imageUrl);
                        article.setPublishDate(publishDate);
                        article.setViewCount(viewCount);
                        article.setCategory(category);

                        // 添加到列表
                        articles.add(article);
                    }
                } finally {
                    cursor.close();
                }
            }

            Log.d(TAG, "搜索文章数量: " + articles.size());
        } catch (Exception e) {
            Log.e(TAG, "搜索文章异常", e);
        }
        
        // 如果没有真实数据，生成一些模拟数据
        if (articles.isEmpty() && keyword != null && !keyword.isEmpty()) {
            Article article = new Article();
            article.setId(1001);
            article.setTitle("搜索结果: " + keyword);
            article.setSummary("这是关于 " + keyword + " 的搜索结果");
            article.setContent("这是关于 " + keyword + " 的详细内容...");
            article.setImageUrl("");
            article.setPublishDate("2024-05-20");
            article.setViewCount(15);
            article.setCategory("搜索");
            articles.add(article);
        }

        return articles;
    }

    @Override
    public boolean saveArticle(Article article) {
        try {
            // 创建ContentValues对象，用于保存数据
            ContentValues values = new ContentValues();
            values.put("title", article.getTitle());
            values.put("summary", article.getSummary());
            values.put("content", article.getContent());
            values.put("image_url", article.getImageUrl());
            values.put("publish_date", article.getPublishDate());
            values.put("view_count", article.getViewCount());
            values.put("category", article.getCategory());
            values.put("user_id", UserSession.getInstance().getUserId());

            // 插入数据到ContentProvider
            Uri uri = contentResolver.insert(ArticleProvider.CONTENT_URI, values);

            Log.d(TAG, "保存文章结果: " + (uri != null ? "成功" : "失败"));

            return uri != null;
        } catch (Exception e) {
            Log.e(TAG, "保存文章异常", e);
            return false;
        }
    }
    
    /**
     * 生成模拟文章数据
     */
    private List<Article> generateMockArticles(int tabType) {
        List<Article> mockArticles = new ArrayList<>();
        
        // 获取当前用户类型
        int userType = UserSession.getInstance().getUserType();
        
        // 根据用户类型和标签类型生成不同的模拟数据
        if (userType == LoginContract.USER_TYPE_BUYER) {
            // 买家端数据
            switch (tabType) {
                case ArticleContract.TAB_FOLLOW:
                    // 买家关注的文章
                    Article followArticle1 = new Article();
                    followArticle1.setId(101);
                    followArticle1.setTitle("【买家】大丰收，红富士苹果获丰收！");
                    followArticle1.setSummary("今年红富士苹果获得丰收，价格优惠");
                    followArticle1.setPublishDate("2024-05-20");
                    followArticle1.setViewCount(56);
                    followArticle1.setCategory("水果");
                    mockArticles.add(followArticle1);
                    break;
                    
                case ArticleContract.TAB_LATEST:
                    // 买家最新文章
                    Article latestArticle1 = new Article();
                    latestArticle1.setId(201);
                    latestArticle1.setTitle("【买家】大丰收，红富士苹果获丰收！");
                    latestArticle1.setSummary("今日果园丰收，红富士苹果喜获丰收！欢迎各位农友前来采摘，价格优惠。");
                    latestArticle1.setPublishDate("2024-05-20");
                    latestArticle1.setViewCount(56);
                    latestArticle1.setCategory("水果");
                    mockArticles.add(latestArticle1);
                    
                    Article latestArticle2 = new Article();
                    latestArticle2.setId(202);
                    latestArticle2.setTitle("【买家】西红柿蔬菜基地");
                    latestArticle2.setSummary("月光红梅，喜获丰收，欢迎各位农友前来交流种植经验！");
                    latestArticle2.setPublishDate("2024-05-19");
                    latestArticle2.setViewCount(42);
                    latestArticle2.setCategory("蔬菜");
                    mockArticles.add(latestArticle2);
                    break;
                    
                case ArticleContract.TAB_MINE:
                    // 买家我的文章
                    Article myArticle1 = new Article();
                    myArticle1.setId(301);
                    myArticle1.setTitle("【买家】我的购买经验分享");
                    myArticle1.setSummary("分享我购买农产品的经验和技巧");
                    myArticle1.setPublishDate("2024-05-18");
                    myArticle1.setViewCount(28);
                    myArticle1.setCategory("经验");
                    mockArticles.add(myArticle1);
                    break;
            }
        } else {
            // 卖家端数据
            switch (tabType) {
                case ArticleContract.TAB_FOLLOW:
                    // 卖家关注的文章
                    Article followArticle1 = new Article();
                    followArticle1.setId(101);
                    followArticle1.setTitle("【卖家】农产品销售技巧分享");
                    followArticle1.setSummary("如何提高农产品销售量，增加收入");
                    followArticle1.setPublishDate("2024-05-20");
                    followArticle1.setViewCount(76);
                    followArticle1.setCategory("销售");
                    mockArticles.add(followArticle1);
                    break;
                    
                case ArticleContract.TAB_LATEST:
                    // 卖家最新文章
                    Article latestArticle1 = new Article();
                    latestArticle1.setId(201);
                    latestArticle1.setTitle("【卖家】大丰收，红富士苹果获丰收！");
                    latestArticle1.setSummary("今日果园丰收，红富士苹果喜获丰收！欢迎各位农友前来采摘，价格优惠。");
                    latestArticle1.setPublishDate("2024-05-20");
                    latestArticle1.setViewCount(56);
                    latestArticle1.setCategory("水果");
                    mockArticles.add(latestArticle1);
                    
                    Article latestArticle2 = new Article();
                    latestArticle2.setId(202);
                    latestArticle2.setTitle("【卖家】西红柿蔬菜基地");
                    latestArticle2.setSummary("月光红梅，喜获丰收，欢迎各位农友前来交流种植经验！");
                    latestArticle2.setPublishDate("2024-05-19");
                    latestArticle2.setViewCount(42);
                    latestArticle2.setCategory("蔬菜");
                    mockArticles.add(latestArticle2);
                    break;
                    
                case ArticleContract.TAB_MINE:
                    // 卖家我的文章
                    Article myArticle1 = new Article();
                    myArticle1.setId(301);
                    myArticle1.setTitle("【卖家】我的野生绿色土豆");
                    myArticle1.setSummary("农家自种野生绿色土豆，无农药绿色食品");
                    myArticle1.setPublishDate("2024-05-18");
                    myArticle1.setViewCount(28);
                    myArticle1.setCategory("蔬菜");
                    mockArticles.add(myArticle1);
                    break;
            }
        }
        
        return mockArticles;
    }
} 